﻿using System;
using System.Data.SqlClient;
using System.Data;

namespace DateCenter.UpdateTool
{
    public class UpdateDirector
    {
        public UpdateDirector(SqlCommand command0, SqlCommand command1)
        {
            this._Command0 = command0;
            this._Command1 = command1;
        }
        private SqlCommand _Command0;
        private SqlCommand _Command1;

        public bool Update(UpdateBase update)
        {
            try
            {
                TruncateTable(_Command1, "Object");
                TruncateTable(_Command1, "ObjectType");
                TruncateTable(_Command1, "Component");

                if (!update.UpdateObjects(_Command0, _Command1)) return false;
                if (!update.UpdateTypes(_Command0, _Command1)) return false;
                if (!update.UpdateSourceComponents(_Command0, _Command1)) return false;
                if (!update.UpdateAdapterComponents(_Command0, _Command1)) return false;
                if (!update.UpdateProcessComponents(_Command0, _Command1)) return false;
                if (!update.UpdateCalculateComponents(_Command0, _Command1)) return false;
                if (!update.UpdateSettings(_Command0, _Command1)) return false;
                if (!update.UpdateValues(_Command0, _Command1)) return false;
                

                string commandString = "";
                commandString += "UPDATE [Object] SET ObjectType = -1 * ObjectType WHERE ObjectType < 0;";
                commandString += "UPDATE [Object] SET BindingSourceId = -1 * BindingSourceId WHERE BindingSourceId < 0;";
                commandString += "UPDATE [Object] SET BindingAdapterId = -1 * BindingAdapterId WHERE BindingAdapterId < 0;";
                commandString += "UPDATE [Object] SET BindingProcessorId = -1 * BindingProcessorId WHERE BindingProcessorId < 0;";
                commandString += "UPDATE [Object] SET BindingCalculatorId = -1 * BindingCalculatorId WHERE BindingCalculatorId < 0;";
                _Command1.CommandText = commandString;
                _Command1.CommandType = CommandType.Text;
                _Command1.ExecuteNonQuery();

                return true;
            }
            catch (Exception ex)
            {
                Logger.GetInstance().Error("数据中心更新失败", ex);
                return false;
            }
        }

        private void TruncateTable(SqlCommand command, string tableName)
        {
            string commandString = "TRUNCATE TABLE [{0}]";
            command.CommandText = string.Format(commandString, tableName);
            command.CommandType = CommandType.Text;
            command.ExecuteNonQuery();
        }
    }
}
